package org.chen.scene.service;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.scene.entity.Attraction;
import org.chen.common.scene.ollama.TourRecommendationResponse;
import org.chen.scene.scheduler.AttractionTourRecommendScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AttractionBatchUpdateService {
    
    @Autowired
    private AttractionService attractionService;

    /**
     * 批量更新数据库（事务方法）
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateDatabase(List<AttractionTourRecommendScheduler.ProcessResult> successResults) {
        try {
            // 构建批量更新的数据
            List<Attraction> updateList = successResults.stream()
                .map(result -> {
                    Attraction attraction = new Attraction();
                    attraction.setPoiId(result.getPoiId());
                    attraction.setVisitHours(String.valueOf(result.getRecommendHours()));
                    return attraction;
                })
                .collect(Collectors.toList());

            // 批量更新
            boolean updated = attractionService.batchUpdateVisitHours(updateList);
            
            if (updated) {
                log.info("批量更新数据库成功，更新{}条记录", successResults.size());
            } else {
                log.error("批量更新数据库失败");
                throw new RuntimeException("批量更新失败");
            }
            
        } catch (Exception e) {
            log.error("批量更新数据库异常", e);
            throw e; // 抛出异常以触发事务回滚
        }
    }

    /**
     * 回退到单个更新（事务方法）
     */
    @Transactional(rollbackFor = Exception.class)
    public void fallbackToSingleUpdate(List<AttractionTourRecommendScheduler.ProcessResult> results) {
        log.warn("回退到单个更新模式");
        
        int successCount = 0;
        List<Exception> errors = new ArrayList<>();
        
        for (AttractionTourRecommendScheduler.ProcessResult result : results) {
            try {
                TourRecommendationResponse recommendation = new TourRecommendationResponse();
                recommendation.setRecommend_Hours(result.getRecommendHours());
                
                attractionService.updateUnAttractionTourRecommend(result.getPoiId(), recommendation);
                successCount++;
                
            } catch (Exception e) {
                log.error("单个更新景点{}失败", result.getPoiId(), e);
                errors.add(e);
            }
        }
        
        log.info("单个更新完成，成功{}条，失败{}条", successCount, errors.size());
        
        // 如果失败率太高，可以选择回滚整个事务
        if (errors.size() > results.size() / 2) {
            throw new RuntimeException("单个更新失败率过高，回滚事务");
        }

    }
}